package com.lagou.edu.dao.impl;

import com.lagou.edu.pojo.Account;
import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.DruidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author 应癫
 */
@Repository("accountDao")// 定义bean标签id，如果不指定值就是 类名首字母小写
public class JdbcAccountDaoImpl implements AccountDao {


    /**
     * @Autowired采取的策略为按照类型注⼊。
     * dao层依赖ConnectionUtils  自动装配
     * 可以加在属性上，可以加在set方法上面，如果加在属性上面set方法就不需要
     * connectionUtils的类型是ConnectionUtils
     */
    @Autowired
    private ConnectionUtils connectionUtils;


    public void init() {
        System.out.println("初始化方法。。。。。。");
    }

    public void destory() {
        System.out.println("销毁方法。。。。。。");
    }

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        //从连接池获取连接   ,改为从线程池里面拿单列的
//        Connection con = DruidUtils.getInstance().getConnection();
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "select * from account where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while(resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();
        // 拿到单列的 数据库连接池不能关闭 ，关了释放了，拿到的就不是一个了
//        con.close();

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {

        //从连接池获取连接   ,改为从线程池里面拿单列的
//        Connection con = DruidUtils.getInstance().getConnection();
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where cardNo=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
        // 拿到单列的 数据库连接池不能关闭 ，关了释放了，拿到的就不是一个了
//        con.close()
        return i;
    }
}
